import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    userRowid: null,
    token: null,
    isLogin: false,
  }),

  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo?.id,

    // 获取用户名
    username: (state) => state.userInfo?.username,

    // 获取用户头像
    avatar: (state) => state.userInfo?.avatar,

    // 获取用户公司
    companyRowid: (state) => state.userInfo?.companyRowid,

    // 检查是否已登录（需要有userRowid）
    hasLogin: (state) => state.isLogin && !!state.userRowid,
  },

  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
      this.isLogin = true
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },

    // 设置userRowid
    setUserRowid(userRowid) {
      this.userRowid = userRowid
      localStorage.setItem('userRowid', userRowid)
    },

    // 设置token
    setToken(token) {
      this.token = token
      const expiryTime = Date.now() + 7 * 24 * 60 * 60 * 1000 // 7天后过期
      localStorage.setItem('token', token)
      localStorage.setItem('tokenExpiry', expiryTime.toString())
    },

    // 登录
    login(userInfo, userRowid) {
      this.setUserInfo(userInfo)
      this.setUserRowid(userRowid)
      // 如果有token也设置
      if (userRowid) {
        this.setToken(userRowid) // 暂时使用userRowid作为token
      }
    },

    // 登出
    logout() {
      this.userInfo = null
      this.userRowid = null
      this.token = null
      this.isLogin = false
      localStorage.removeItem('userInfo')
      localStorage.removeItem('userRowid')
      localStorage.removeItem('token')
      localStorage.removeItem('tokenExpiry')
    },

    // 检查token是否过期
    isTokenExpired() {
      const expiryTime = localStorage.getItem('tokenExpiry')
      if (!expiryTime) return true
      return Date.now() > parseInt(expiryTime)
    },

    // 初始化用户状态（从本地存储恢复）
    initUserState() {
      try {
        const userInfoStr = localStorage.getItem('userInfo')
        const userRowid = localStorage.getItem('userRowid')
        const token = localStorage.getItem('token')

        // 检查token是否过期
        if (this.isTokenExpired()) {
          this.logout()
          return false
        }

        if (userInfoStr && userRowid) {
          this.userInfo = JSON.parse(userInfoStr)
          this.userRowid = userRowid
          this.token = token
          this.isLogin = true
          return true
        }
      } catch (error) {
        console.error('初始化用户状态失败:', error)
        this.logout()
      }
      return false
    },

    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = { ...this.userInfo, ...userInfo }
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },
  },
})
